package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public List<CategoryDTO> queryCategoryByIds(List<Long> ids) {
        return CategoryDTO.convertEntityList(this.listByIds(ids));
    }

    @Override
    public List<CategoryDTO> queryCategoryByPid(Long pid) {

        //select * from tb_category where parent_id = #{pid}
        List<Category> categories = query()
                .eq("parent_id", pid)
                .list();

        return  CategoryDTO.convertEntityList(categories);
    }

    @Override
    public List<CategoryDTO> queryCategoryByBrand(Long bid) {

        //select * from tb_category_brand where brand_id = #{bid}
        List<CategoryBrand> categoryBrands =
                this.categoryBrandService
                        .query()
                        .eq("brand_id", bid)
                        .list();

        //从分类品牌的集合中获取所有的分类id
        List<Long> cids = categoryBrands
                .stream()
                .map(CategoryBrand::getCategoryId)
                .collect(Collectors.toList());

        return queryCategoryByIds(cids);
    }
}
